﻿/*
 * author;wangsir收集张刚以前的代码
 * Date:2009-8-31
 * fucntion:用于序列化、反序列化实体。
 *          Base64Serialization.Serialize(object obj);//序列化对象
 *          Base64Serialization.Deserialize(string base64String);//反序列化对象。
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace ARS.PublicTool.DataHandle
{
    /// <summary>
    /// 序列化帮助类
    /// </summary>
    public class Base64Serialization
    {
        private Base64Serialization()
        {
        }
        /// <summary>
        /// 将对象序列化为 Base64 的字符串形式
        /// 失败返回 null
        /// </summary>
        /// <param name="obj">对象(必须是 Serializable 的对象实例)</param>
        public static string Serialize(object obj)
        {
            MemoryStream ms = null;
            string base64String = null;

            try
            {
                IFormatter bf = new BinaryFormatter();
                ms = new MemoryStream();
                bf.Serialize(ms, obj);
                byte[] data = ms.ToArray();
                base64String = Convert.ToBase64String(data, 0, data.Length);
            }
            finally
            {
                ms.Close();
            }
            return base64String;
        }
        /// <summary>
        /// Base64 的字符串反序列化为对象实例
        /// 失败返回 null
        /// </summary>
        /// <param name="base64String">字符串</param>
        public static T Deserialize<T>(string base64String)
        {
            byte[] data = new byte[0];
            object obj = null;

            if (base64String != null)
            {
                try
                {
                    data = Convert.FromBase64String(base64String);
                }
                finally
                {
                    if (data.Length > 0)
                    {
                        MemoryStream ms = null;

                        try
                        {
                            IFormatter bf = new BinaryFormatter();
                            ms = new MemoryStream(data);
                            obj = bf.Deserialize(ms);
                        }
                        finally
                        {
                            if (ms != null)
                                ms.Close();
                        }
                    }
                }
            }
            return (T)obj;
        }
    }
}
